import { generateDeclarationFile } from './utils.js';
import { Extractor, ExtractorConfig } from '@microsoft/api-extractor';
import { resolve } from 'node:path';
import { mkdir, writeFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';

export default async function buildPluginUi() {
  // 确保目标目录存在
  const outDir = resolve(process.cwd(), 'tmp/plugin-ui/unbundled-types');
  const dtsPath = resolve(outDir, 'index.d.ts');
  
  console.log(`Creating directory: ${outDir}`);
  await mkdir(outDir, { recursive: true });

  try {
    console.log('Generating declaration file...');
    generateDeclarationFile(
      {
        [resolve(process.cwd(), 'src/plugin-ui/index.tsx')]: 'index',
      },
      outDir,
    );
    console.log('Declaration file generated successfully.');
  } catch (error) {
    console.error('Error generating declaration file:', error);
    
    // 如果声明文件生成失败，创建一个空的声明文件
    console.log(`Creating empty declaration file at ${dtsPath}`);
    await writeFile(dtsPath, `// Empty declaration file created as fallback\nexport type ToolbarContext = any;\n`);
  }

  // 确保文件存在
  if (!existsSync(dtsPath)) {
    console.log(`Declaration file not found at ${dtsPath}, creating a minimal one...`);
    await writeFile(dtsPath, `// Minimal declaration file created\nexport type ToolbarContext = any;\n`);
  } else {
    console.log(`Declaration file exists at ${dtsPath}`);
  }

  console.log('Loading API Extractor config...');
  const extractorConfig = ExtractorConfig.loadFileAndPrepare(
    resolve(process.cwd(), 'api-extractor-configs/plugin-ui.json'),
  );

  console.log('Invoking API Extractor...');
  Extractor.invoke(extractorConfig, {});
  console.log('API Extractor completed successfully.');
}
